package com.example.jedis.controller;

import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Transaction;

/**
 * 秒杀案例
 *
 * @author <a href="920786312@qq.com">周飞</a>
 * @class: RedisTestController
 * @date 2022/2/3 14:11
 * @Verson 1.0 -2022/2/3 14:11
 * @see
 */

public class DoSecKill_v3 {



    public static void main(String[] args) throws IOException {





        doSecKill("201","111");
    }

    static String secKillScript =
        "local userId=KEYS[1]; \n" +
        "local prodId=KEYS[2];\n" +
        "local stock_key=\"stock:\"..prodId;\n" +
        "local success_user_key=\"success:\"..prodId; \n" +
        "local userExists=redis.call(\"sismember\",success_user_key,userId);\n" +
        "if tonumber(userExists)==1 then \n" +
        "   return 2;\n" +
        "end\n" +

        "local num= redis.call(\"get\" ,stock_key);\n" +
        "if tonumber(num)<=0 then \n" +
        "  return 0; \n" +
        "else \n" +

        "  redis.call(\"decr\",stock_key);\n" +
        "  redis.call(\"sadd\",success_user_key,userId);\n" +
        "end\n" +
        "return 1 " ;


    public static boolean doSecKill(String uid,String prodid) throws IOException {


        Jedis jedis=getJedis_v1();

        //String sha1=  .secKillScript;
        String sha1=  jedis.scriptLoad(secKillScript);
        Object result= jedis.evalsha(sha1, 2, uid,prodid);

        String reString=String.valueOf(result);
        if ("0".equals( reString )  ) {
            System.err.println("已抢空！！");
        }else if("1".equals( reString )  )  {
            System.out.println("抢购成功！！！！");
        }else if("2".equals( reString )  )  {
            System.err.println("该用户已抢过！！");
        }else{
            System.err.println("抢购异常！！");
        }
        jedis.close();
        return true;
    }
    /**
     * 构建Jedis
     *
     * @author <a href="920786312@qq.com">周飞</a>
     * @since 2022/2/3 15:18
     */
    public static Jedis getJedis_v1() {
        // 2 连接redis
        return new Jedis("192.168.187.138", 6379);
    }
    
}